from django.shortcuts import render
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.viewsets import GenericViewSet, ReadOnlyModelViewSet
from rest_framework.decorators import action
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from .models import Product,HotRecommend,HistoryProduct
from django.core.cache import cache
from buyHigh.utils.buyHighResponse import APIResponse
from .serializer import HotRecommendSerializer,ProductSerializer,IndexSerializer
from .paginations import PageNumberPagination
from haystack.query import SearchQuerySet
from itertools import chain
from random import shuffle
from rest_framework.mixins import RetrieveModelMixin
from drf_haystack.viewsets import HaystackViewSet
from .models import Product
from .serializer import IndexSerializer
# Create your views here.
class ProductView(GenericViewSet,):
    """
        es实现的猜你喜欢
    """
    serializer_class = ProductSerializer
    queryset = Product.objects.all()
    pagination_class = PageNumberPagination
    permission_classes =[IsAuthenticatedOrReadOnly]
    authentication_classes = [JSONWebTokenAuthentication]
    @action(methods=['get'], detail=False)
    def get_guss_like_products(self, request):
        # 获取猜你喜欢商品
        # 获取用户未登录的情况下的推荐列表
        print(request.user)
        if not request.user.is_authenticated:
            print("用户未登录")
            # 推荐关联不为空，说明是推荐商品，可以用于未登录用户的猜你喜欢
            pruduct_list = Product.objects.filter(hot_recommend__isnull=False).order_by('sold_quantity')
            page = self.paginate_queryset(pruduct_list)
            if page is not None:
                serializer = ProductSerializer(instance=page, many=True)
                return self.get_paginated_response(serializer.data)
            # 可以根据用户的历史记录等进行推荐，后续添加，目前先根据用户的浏览记录进行推荐
            return APIResponse(status=200, statusCode=200, code=200, message='没有更多数据了')
        # 有缓存的情况下走缓存
        guess_cache_key = str(request.user.id) + "_cache_guess_products"
        cache_product_list=cache.get(guess_cache_key)
        if cache_product_list:
            print("有缓存的情况下走缓存")
            page = self.paginate_queryset(cache_product_list)
            if page is not None:
                serializer = ProductSerializer(instance=page, many=True)
                return self.get_paginated_response(serializer.data)
        # 获取用户登录的情况下的推荐列表
        # 获取用户的历史记录
        history_project_list = HistoryProduct.objects.filter(user=request.user)
        # 用户没有历史记录的情况下
        if not history_project_list:
            """
                后续可添加根据购物车等进行推荐扩展，目前根据历史记录的商品分类进行推荐
            """
            pruduct_list = Product.objects.filter(hot_recommend__isnull=False).order_by('sold_quantity')
            serializer = ProductSerializer(instance=pruduct_list, many=True)
            return APIResponse(data=serializer.data, status=200, statusCode=200, code=200, message='success')
        project_category_list=history_project_list.values_list('product__category',flat=True)
        # 去重
        project_category_list=list(set(project_category_list))
        # 按照销量排序
        pruduct_list=Product.objects.filter(category__in=project_category_list).order_by('sold_quantity')[:300]
        cache.set(guess_cache_key, pruduct_list)
        page = self.paginate_queryset(pruduct_list)
        if page is not None:
            serializer = ProductSerializer(instance=page, many=True)
            return self.get_paginated_response(serializer.data)
        return APIResponse( status=200, statusCode=200, message='没有更多数据啦!')
    @action(methods=['get'], detail=False,url_path='get_product_detail/(?P<pk>\d+)')
    def get_product_detail(self, request, *args, **kwargs):
        obj = self.get_object()
        serializer = ProductSerializer(instance=obj)
        if not serializer.data:
            # 保存用户的历史记录
            return APIResponse(status=404, statusCode=404, message='商品不存在')
        if request.user.is_authenticated:
            # 如果用户登录的情况下，保存用户的历史记录
            HistoryProduct.objects.create(user=request.user,product=obj)
        return APIResponse(data=serializer.data, status=200, statusCode=200, message='success')





class HotRecommendView(GenericViewSet):
    """
        推荐内容和商品
    """
    pagination_class = PageNumberPagination
    serializer_class = HotRecommendSerializer
    @action(methods=['get'],detail=False)
    def get_recommend_products(self,request):
        # 获取推荐列表和商品
        hot_recommend_list=HotRecommend.objects.filter(pid=None)
        ser=HotRecommendSerializer(hot_recommend_list,many=True)
        return APIResponse(data=ser.data,status=200,statusCode=200,code=200,message='success')
    # 捕获id参数
    @action(methods=['get'],detail=False,url_path='get_hot_detail/(?P<pk>\d+)')
    def get_hot_detail(self,request,*args,**kwargs):
        # 获取推荐用户点击父级推荐对象的id
        pk=kwargs.get('pk')
        # 获取需要返回的数据
        instance=HotRecommend.objects.filter(pid=pk)
        ser=HotRecommendSerializer(instance,many=True,context={"detail":True})
        return APIResponse(data=ser.data,status=200,statusCode=200,code=200,message='success')
    @action(methods=['get'],detail=False,url_path='get_hot_detail_products/(?P<pk>\d+)')
    def get_hot_detail_products(self,request,*args,**kwargs):
        # 获取用户点击的推荐对象的id，这个id是子级推荐对象的id
        recommend_obj_pk=kwargs.get('pk')
        instance=Product.objects.filter(hot_recommend__id=recommend_obj_pk)
        page = self.paginate_queryset(instance)
        if page is not None:
            serializer = ProductSerializer(instance=page, many=True)
            return self.get_paginated_response(serializer.data)
        else:
            return APIResponse(status=200,statusCode=200,code=200,message='没有更多数据啦!')




class ProductSearchView(HaystackViewSet):
    """
        商品搜索
    """
    index_models = [Product]
    serializer_class = IndexSerializer
    pagination_class = PageNumberPagination


